package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: HuoXu
 * @Date: 2023/09/16/23:44
 * @Description: 快乐跳跳虎
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理订单在十五分钟内未进行支付的情况
     */
    @Scheduled(cron = "0 * * * * ?") //每分钟触发一次
    public void orderTimeOut() {
        log.info("定时处理超时订单,{}", LocalDateTime.now());
        /*处理思路
        * 1、查询数据库是否含有超时订单，如果有才进行处理
        * 2、如果有就进行遍历，然后重新设置新的值然后进行数据库更新
        * */
        //获取当前时间减去十五分钟
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> list=orderMapper.selectByStatusAndOrderTime(Orders.PENDING_PAYMENT,time);
        if(list!=null && list.size()>0) {
            for (Orders orders : list) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时，系统已为您自动取消");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }
    }

    /**
     * 处理订单一直处于配送中的情况
     */
    @Scheduled(cron = "0 0 1 * * ?") //每天凌晨一点触发一次
    public void orderDeliveryInProgress(){
        log.info("定时一直处于派送订单,{}", LocalDateTime.now());
        //获取当前时间减去十五分钟
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> list=orderMapper.selectByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS,time);
        if(list!=null && list.size()>0) {
            for (Orders orders : list) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }
}
